#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
    //printf("stdin: %d\n", stdin->_fileno);
    //printf("stdout: %d\n",stdout->_fileno);
    //printf("stderr: %d\n", stderr->_fileno);

    //printf("\n\n");
    //close(0);
    //close(2);
    //close(1);
//重定向
    
    //int fd = open("log.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
  //  int fd = open("log1.txt", O_RDONLY);//只读
    int fd = open(argv[1], O_RDONLY);//只读
    if(fd < 0) exit(1);
    dup2(fd, 0);
    close(fd);
    //默认向显示器输出
    while(1)
    {
        char buffer[256];
        if(!fgets(buffer, sizeof(buffer), stdin)) break;
        //stdin 是标准输入流，底层对应文件描述符 0。由于 dup2 已将 0 重定向到 log.txt，因此 fgets 实际是从 log.txt 中读取内容。
        printf("%s", buffer);
    }


   // printf("fd: %d\n", fd);
   // printf("helle, world\n");
   // printf("helle, world\n");
   // printf("helle, world\n");
   // fprintf(stdout, "hello, stdout\n");
   // fprintf(stdout, "hello, stdout\n");
    //fprintf(stdout, "hello, stdout\n");

   // const char *msg = "hello, msg\n";
   // write(fd, msg, strlen(msg));
    //int fd = open("log1.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //printf("%d\n", fd);
    //close(fd);



    //umask(0);
    //int fd1 = open("log1.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //int fd2 = open("log2.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //int fd3 = open("log3.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //int fd4 = open("log4.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);
    //if(fd1 < 0)exit(1);
    //if(fd2 < 0)exit(1);
    //if(fd3 < 0)exit(1);
    //if(fd4 < 0)exit(1);

    //printf("fd1: %d\n", fd1);
    //printf("fd2: %d\n", fd2);
    //printf("fd3: %d\n", fd3);
    //printf("fd4: %d\n", fd4);
//为//什么打印是：3,4，5,6呢, 因为管理文件的是一个指针数组，下标为0，1，2默认打开标准输入，标准输出，标准错误文件
    //close(fd1);
    //close(fd2);
    //close(fd3);
    //close(fd4);

    //umask(0);
    ////int fd = open("log.txt", O_CREAT | O_WRONLY | O_TRUNC, 0666);//覆盖写入
    ////int fd = open("log.txt", O_CREAT | O_WRONLY | O_APPEND, 0666);//追加写入
    //int fd = open("log.txt", O_RDONLY);//只读
    //if(fd < 0) exit(1);

    //printf("fd:%d\n", fd);
    //while(1)
    //{
    //    char buffer[256];
    //    int n = read(fd, buffer, sizeof(buffer)-1);
    //    if(n > 0)
    //    {
    //        buffer[n] = 0;
    //        printf("%s", buffer);
    //    }
    //    else if(n == 0)
    //    {
    //        break;
    //    }
    //}


    //const char *msg = "Today is raining!\n";
    //int cnt = 5;
    //while(cnt)
    //{
    //    write(fd, msg, strlen(msg));
    //    cnt--;
    //}

    //close(fd);
    return 0;
}
